<?php

namespace Admin\Controller;
use Common\Api\Category;
/**
* 用户权限控制器
*/
class AuthController extends CommonController
{
	
	public function index() {
		$this->_list( M('auth_group') );
		$this->display();
	}
    
    //新增用户组
	public function createGroup() {
		if(IS_POST) {
			if(!I('post.title')) $this->error('请填写名称！');
			if(!M('auth_group')->add(I('post.'))) {
				$this->error('新增失败！');
			}else{
				$this->success('新增成功！', U('index'));
			}
		}else{
			$this->display();
		}
	}

	//禁用用户组
	public function lockGroup() {
		if(IS_AJAX) {
			if(I('get.type') == 1) {
				if(!M('auth_group')->where(array('id'=>I('get.group_id')))->setField('status', 1) ) {
					$this->error('操作失败！');
				}else{
					$this->success('操作成功！');
				}
			}else{
				if(!M('auth_group')->where(array('id'=>I('get.group_id')))->setField('status', 0) ) {
					$this->error('操作失败！');
				}else{
					$this->success('操作成功！');
				}
			}
		}else{
			$this->display();
		}
	}

	//访问权限
	public function access() {
		$Category = new Category();
		$rules = M('AuthRule')->select();

		$ruleStr = M('AuthGroup')->where( array('id'=> I('get.group_id')) )->getField('rules');
		$ruleArr = explode(',', $ruleStr);

		$this->assign('ruleArr', $ruleArr);
        $this->assign('rules', $Category->unlimitedForLayer($rules));
		$this->display();
	}
    
    //保存用户权限
	public function saveAccess() {
		if(IS_AJAX) {
			$rules = implode(',', $_POST['rules']);
			$res = M('AuthGroup')->where( array('id'=>I('post.group_id')) )->setField('rules', $rules);
			if( !$res ) {
				$this->error('操作失败！');
			} else {
				$this->success('操作成功！', U('index'));
			}
		}else{
			$this->display();
		}
	}
    //权限规则
	public function rules() {
		$Category = new Category();
		$rules = M('AuthRule')->select();
        $this->assign('rules', $Category->unlimitedForLevel($rules));
		$this->display();
	}
    //新增权限规则
	public function addRules() {
		if(IS_AJAX) {
			$db = D('AuthRule');
			if(!$db->create()) {
				$this->error($db->getError());
			}else{
				if(!$db->add()) {
					$this->error('新增失败！');
				}else{
					$this->success('新增成功！', U('rules'));
				}
			}
		}else{
			$this->display();
		}
	}

	//用户授权
	public function group() {
		if( I('get.uid') == C('ADMINISTRATOR_USER') ) {
			$this->error('不能对超级管理员进行操作！');
		}
		if(IS_AJAX) {
			M('AuthGroupAccess')->where(array('uid'=>I('post.uid')))->delete();
			if( !M('AuthGroupAccess')->add(I('post.')) ) {
				$this->error('操作失败！');
			}else{
				$this->success('操作成功！');
			}
		}else{
			$this->group = M('AuthGroup')->where( array('status'=>1) )->select();
		    $this->display();
		}
	}
}